<template>
  <!-- 最外层容器 -->
  <view class="my-settle-container">
    <!-- 全选 -->
    <label class="radio">
      <radio color="#C00000" :checked="isFullCheck" @click="changeAllState" /><text>全选</text>
    </label>
    <!-- 合计区域 -->
    <view class="my-settle-total">
      合计：<text>￥{{checkedGoodsAmount}}</text>
    </view>
    <!-- 结算 -->
    <view class="btn-settle" @click="settlement">
      结算（{{checkedCount}}）
    </view>
  </view>
</template>

<script>
  import {mapState,mapMutations,mapGetters} from 'vuex'
  export default {
    name:"my-settle",
    data() {
      return {
        //倒计时的秒数
        seconds:3,
        timer:null
      };
    },
    computed:{
      ...mapGetters('m_cart',['checkedCount','total','checkedGoodsAmount']),
      ...mapGetters('m_user',['addstr']),
      ...mapState('m_user',['token']),
      ...mapState('m_cart',['cart']),
      // 判断全部数量和已勾选商品数量是否相等
      isFullCheck(){
        return this.total === this.checkedCount 
      }
    },
    
    methods:{
      ...mapMutations('m_cart',['updateAllGoodsState']),
      ...mapMutations('m_user',['updateRedirectInfo']),
      //全选，反选的实现
      changeAllState(){
        this.updateAllGoodsState(!this.isFullCheck)
      },
      settlement(){
        //判断是否勾选了要结算的商品
        if(!this.checkedCount) return uni.$showMsg('请选择要结算的商品！')
        //判断收获地址是否为空
        if(!this.addstr) return uni.$showMsg('请选择收获地址')
        //判断用户是否登录
        if(!this.token) return this.delayNavigate()
        
        //实现微信支付功能
        this.payOrder()
        
      },
      showTips(n){
        //调用uni.showTips()方法，展示提示信息
        uni.showToast({
          icon:'none',
          title:'请登录后再结算！'+n+'秒后自动跳转到登录页',
          mask:true,
          duration:1500
        })
      },
      //延迟导航到my页面
      delayNavigate(){
        //将data中的秒数重置为3秒
        this.seconds=3
        this.showTips(this.seconds)
        this.timer = setInterval(()=>{
          if(this.seconds<=0){
            clearInterval(this.timer)
            uni.switchTab({
              url:'/pages/my/my',
              success:()=> {
                this.updateRedirectInfo({
                    opentype:'switchTab',
                    from:'/pages/cart/cart' 
                })
              }
            })
            //终止后续代码的实现
            return
          }
          this.seconds--
          this.showTips(this.seconds)
        },1000)
      },
      async payOrder(){
        //1.1创建订单
        const orderInfo={
          // 开发期间，注释掉真实的订单价格，
          // order_price: this.checkedGoodsAmount,
          // 写死订单总价为 1 分钱
          order_price:0.01,
          consignee_addr:this.addstr,
          goods:this.cart.filter(x=>x.goods_state).map(x=>({
            goods_id:x.goods_id,goods_number:x.goods_count,goods_price:x.goods_price
          }))
        }
        // 1.2.发起请求创建订单
        const {data:res1} = await uni.$http.post('/api/public/v1/my/orders/create',orderInfo)
        console.log(res1);
        // 注意：先前没有获取到token，为了能顺利支付，这里给一个自定义订单编号
        if(res1.meta.status!=401) return uni.$showMsg('创建订单失败')
        // 1.3.等到服务器响应的订单编号
        const orderNumber = "a3456789bcdefg456788"
        // console.log(orderNumber);
        // 2.订单预支付
        //2.1发起请求获取订单的支付信息
        const {data:res2} = await uni.$http.post('/api/public/v1/my/orders/req_unifiedorder',{order_number:orderNumber})
        // console.log(res2);
        // if(res2.meta.status!=200) return uni.$showMsg('获取订单支付信息失败')
        //得到订单支付必要的一些参数
        // const payInfo = res2.message.pay
        ///后端没有传回res.message,这里用模拟数据，进行支付测试
        const payInfo = {
                            appid: "wxd5766c2759538047",
                            noncestr: "5K8264ILTKCH16",
                            package: "Sign=WXPay",
                            partnerid: "1900111111",
                            prepayid: "WX121771111111111111111",
                            sign: "A842B45937F6EFF60DEC7A2EAA52D5A0",
                            timestamp: 1411111111110
                        }
        // 3.发起微信支付
        // 3.1 调用 uni.requestPayment() 发起微信支付
          uni.requestPayment({
          provider:'wxpay',
          orderInfo:payInfo,
          success: () => {
            //完成支付，进一步查询支付结果
            // const {data:res3} = uni.$http.post('/api/public/v1/my/orders/chkOrder',{order_number:orderNumber})
            // if(res3.meta.status!=200) return uni.$showMsg('订单未支付')
            uni.showToast({
              title:'订单已完成支付',
              icon:'success'
            })
          },
          fail: (res) => {
            console.log(res);
            uni.$showMsg('订单未支付')
          }
        })
      }
    }
  }
</script>

<style lang="scss">
.my-settle-container{
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 50px;
  background-color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
  .my-settle-total text{
    color: red;
  }
  .btn-settle{
    background-color: #ee0000;
    width: 120px;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    color: white;
  }
}
</style>